import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Card, Form, Input, Row, Space } from 'antd';
import { flatten, forEach, head, includes, last, map, toPairs, values } from 'lodash';
import { memo, useEffect } from 'react';
const Storage = () => {
  const [form] = Form.useForm();

  const onFinish = (value: any) => {
    const oldStorage = getAllStorage();
    const newStorage = flatten(values(value));

    forEach(
      map(oldStorage, 'key'),
      k => {
        if (!includes(map(newStorage, 'key'), k)) {
          localStorage.removeItem(k)
        }
      }
    );

    forEach(
      newStorage,
      i => localStorage.setItem(i.key, i.value)
    );
  };

  const clearHandle = () => {
    localStorage.clear();
    form.setFieldsValue({
      storage: []
    });
  };

  // 获取所有storage
  const getAllStorage = () => {
    const allStorage: Record<string, any>[] = [];

    forEach(
      toPairs(localStorage),
      i => allStorage.push({ key: head(i), value: last(i) })
    );
    return allStorage;
  };

  useEffect(() => {
    form.setFieldsValue({
      storage: getAllStorage()
    });

    return () => {
      clearHandle();
    }
  }, []);

  return (
    <Card>
      <Row>
        <Form
          form={form}
          onFinish={onFinish}
          autoComplete='off'
        >
          <Form.List name='storage'>
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align='baseline'>
                    <Form.Item
                      {...restField}
                      name={[name, 'key']}
                      rules={[{ required: true, message: '此项必填！' }]}
                    >
                      <Input placeholder='Storage Key' />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'value']}
                      rules={[{ required: true, message: '此项必填！' }]}
                    >
                      <Input placeholder='Storage Value' />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
                <Form.Item>
                  <Button type='dashed' onClick={() => add()} block icon={<PlusOutlined />}>添加</Button>
                </Form.Item>
              </>
            )}
          </Form.List>
          <Form.Item>
            <Space>
              <Button type='primary' htmlType='submit'>确定</Button>
              <Button onClick={clearHandle}>清空</Button>
            </Space>
          </Form.Item>
        </Form>
      </Row>
    </Card>
  );
};

export default memo(Storage);